package logger

import (
	"fmt"
	format "github.com/antonfisher/nested-logrus-formatter"
	log "github.com/sirupsen/logrus"
	"os"
	"path"
	"runtime"
	"strings"
	"time"
)

var Log *log.Logger

func InitLog() {
	Log = New()
}

func New(order ...interface{}) *log.Logger {
	Logger := log.New()
	Logger.SetOutput(os.Stdout)
	var fieldsOrder []string
	if order != nil {
		fieldsOrder = order[0].([]string)
	} else {
		fieldsOrder = []string{}
	}
	Logger.SetFormatter(&format.Formatter{
		FieldsOrder:     fieldsOrder,
		TimestampFormat: time.RFC3339,
		ShowFullLevel:   true,
		CallerFirst:     true,
		HideKeys:        true,
		CustomCallerFormatter: func(f *runtime.Frame) string {
			s := strings.Split(f.Function, ".")
			funcName := s[len(s)-1]
			return fmt.Sprintf(" [%s:%d][%s]", path.Base(f.File), f.Line, funcName)
		},
	})
	Logger.SetReportCaller(true)
	return Logger
}

func WithField(key string, value interface{}) *log.Entry {
	return Log.WithField(key, value)
}

func WithFields(fields Fields) *log.Entry {
	fieldsNew := log.Fields(fields)
	return Log.WithFields(fieldsNew)
}

func Warning(args ...interface{}) {
	Log.Warning(args)
}

func Warn(args ...interface{}) {
	Log.Warn(args)
}

func Fatal(args ...interface{}) {
	Log.Fatal(args)
}

func Fatalf(format string, args ...interface{}) {
	Log.Fatalf(format, args)
}

func Info(args ...interface{}) {
	Log.Info(args)
}

func SetLevel(level log.Level) {
	Log.SetLevel(level)
}

func Level(level uint8) log.Level {
	return log.Level(level)
}

type Fields log.Fields

func WithError(err error) *log.Entry {
	return Log.WithError(err)
}

func Error(args ...interface{}) {
	Log.Error(args)
}

func Errorf(format string, args ...interface{}) {
	Log.Errorf(format, args)
}
